package com.sandking.tools;

import java.io.UnsupportedEncodingException;
import java.util.Random;

/**
 * @UserName : SandKing
 * @DataTime : 2012-9-5 下午4:33:12
 * @Description ：随机工具类
 */
public class SK_Random {
	private static Random random = new Random(System.currentTimeMillis());

	private static final String getChinese() {
		String str = null;
		int highPos, lowPos;
		highPos = (176 + Math.abs(random.nextInt(39)));
		lowPos = 161 + Math.abs(random.nextInt(93));
		byte[] b = new byte[2];
		b[0] = (new Integer(highPos)).byteValue();
		b[1] = (new Integer(lowPos)).byteValue();
		try {
			str = new String(b, "GB2312");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * 随机固定长度中文
	 * 
	 * @param length
	 * @return
	 */
	public static final String getFixedLengthChinese(final int length) {
		String str = "";
		for (int i = length; i > 0; i--) {
			str = str + SK_Random.getChinese();
		}
		return str;
	}

	/**
	 * 范围段随机
	 * 
	 * @param start
	 * @param end
	 * @return
	 */
	public static final String getRandomLengthChiness(final int start,
			final int end) {
		String str = "";
		int length = new Random().nextInt(end + 1);
		if (length < start) {
			str = getRandomLengthChiness(start, end);
		} else {
			for (int i = 0; i < length; i++) {
				str = str + getChinese();
			}
		}
		return str;
	}

	/**
	 * 范围内随机数字
	 * 
	 * @param min
	 * @param max
	 * @return
	 */
	public static final int randInt(final int min, final int max) {
		if (max < min)
			return 0;
		if (max == min)
			return min;
		return (Math.abs(random.nextInt()) % (max - min + 1)) + min;
	}

	/**
	 * 100为基数随机
	 * 
	 * @param n
	 * @return
	 */
	public static final boolean randPercent(final int n, final int max) {
		int x = randInt(1, max);
		if (x <= n)
			return true;
		return false;
	}

	public static final char[] D26 = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
			.toCharArray();
	public static final char[] X26 = ("abcdefghijklmnopqrstuvwxyz")
			.toCharArray();
	public static final char[] X36 = ("0123456789abcdefghijklmnopqrstuvwxyz")
			.toCharArray();
	public static final char[] D36 = ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
			.toCharArray();
	public static final char[] E62 = ("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
			.toCharArray();

	/**
	 * 随机字符串
	 * 
	 * @param length
	 * @param numbersAndLetters
	 * @return
	 */
	public static final String randomString(int length,
			final char[] numbersAndLetters) {
		if (length < 1) {
			return null;
		}
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[random
					.nextInt(numbersAndLetters.length - 1)];
		}
		return new String(randBuffer);
	}
}
